/*
 * @Author: xzx
 * @Date: 2021-11-04 14:07:02
 * @LastEditors: xzx
 * @LastEditTime: 2021-11-04 14:44:24
 * @Description: 佛
 * @FilePath: \hooks\src\context\count.jsx
 */

import React, { createContext, useReducer } from 'react';

// 创建 context
export const CountContext = createContext({});

const initialState = { count: 0 };

// reducer
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'reset':
      return { count: 0 };
    default:
      throw new Error();
  }
}

/**
 * 创建一个 Count 组件
 * Count 组件包裹的所有子组件都可以通过调用 CountContext 访问到 value
 */
export const Count = (props) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return <CountContext.Provider value={{ state, dispatch }}>{props.children}</CountContext.Provider>;
};
